# -*- coding: utf-8 -*-
"""
推荐系统 - 视图函数
"""

from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from .models import UserActivityView, UserInterestTag
from activities.models import Activity
import json


@login_required
@require_http_methods(["GET"])
def api_recommended_activities(request):
    """获取推荐活动API"""
    user = request.user
    
    # 获取用户兴趣标签
    interest_tags = UserInterestTag.objects.filter(user=user).order_by('-weight')[:5]
    
    if interest_tags.exists():
        # 基于兴趣标签推荐
        tag_names = [tag.tag_name for tag in interest_tags]
        
        # 查找包含这些标签的活动（简化版，实际应该更复杂）
        activities = Activity.objects.filter(
            status='published',
            activity_type__name__in=tag_names
        ).order_by('-created_at')[:10]
    else:
        # 默认推荐热门活动
        activities = Activity.objects.filter(
            status='published'
        ).order_by('-view_count')[:10]
    
    results = [{
        'id': a.id,
        'title': a.title,
        'description': a.description,
        'cover_image': a.cover_image,
        'activity_type': {
            'id': a.activity_type.id if a.activity_type else None,
            'name': a.activity_type.name if a.activity_type else '其他'
        },
        'start_time': a.start_time.isoformat(),
        'location_name': a.location_name,
        'current_participants': a.current_participants,
        'max_participants': a.max_participants,
        'is_free': a.is_free,
        'fee': str(a.fee),
        'view_count': a.view_count,
        'rating_average': float(a.rating_average),
    } for a in activities]
    
    return JsonResponse({
        'code': 200,
        'data': {
            'results': results
        }
    })


@login_required
@require_http_methods(["POST"])
def api_record_view(request, activity_id):
    """记录用户浏览行为API"""
    try:
        activity = get_object_or_404(Activity, id=activity_id)
        data = json.loads(request.body)
        
        # 获取或创建浏览记录
        view_record, created = UserActivityView.objects.get_or_create(
            user=request.user,
            activity=activity,
            defaults={
                'source': data.get('source', 'other'),
                'device_type': data.get('device_type', ''),
                'ip_address': get_client_ip(request),
            }
        )
        
        if not created:
            # 更新浏览次数
            view_record.increment_view(
                duration=data.get('duration', 0),
                source=data.get('source', 'other'),
                device_type=data.get('device_type', ''),
                ip_address=get_client_ip(request)
            )
        
        # 更新用户兴趣标签（简化版）
        if activity.activity_type:
            update_interest_tag(request.user, activity.activity_type.name)
        
        return JsonResponse({
            'code': 200,
            'message': '记录成功'
        })
        
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'记录失败：{str(e)}'
        }, status=500)


@login_required
@require_http_methods(["GET"])
def api_user_interest_tags(request):
    """获取用户兴趣标签API"""
    tags = UserInterestTag.objects.filter(user=request.user).order_by('-weight')
    
    results = [{
        'tag_name': t.tag_name,
        'weight': float(t.weight),
        'from_views': float(t.from_views),
        'from_registrations': float(t.from_registrations),
        'from_comments': float(t.from_comments),
        'from_ratings': float(t.from_ratings),
    } for t in tags]
    
    return JsonResponse({
        'code': 200,
        'data': {
            'results': results
        }
    })


# ========== 辅助函数 ==========

def get_client_ip(request):
    """获取客户端IP地址"""
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        ip = x_forwarded_for.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR')
    return ip


def update_interest_tag(user, tag_name):
    """更新用户兴趣标签"""
    try:
        tag, created = UserInterestTag.objects.get_or_create(
            user=user,
            tag_name=tag_name,
            defaults={
                'from_views': 0.1,
            }
        )
        
        if not created:
            # 增加浏览权重
            tag.from_views = min(1.0, tag.from_views + 0.05)
            tag.update_weight()
    except Exception as e:
        print(f'更新兴趣标签失败: {e}')
